import {ResourceLoader} from "./js/base/ResourceLoader.js";
import {BackGround} from "./js/runtime/BackGround.js";
import {DataStore} from "./js/base/DataStore.js";
import {Director} from "./js/Director.js";
import {Land} from "./js/runtime/Land.js";
import {Birds} from "./js/player/Birds.js";
import {StartButton} from "./js/player/StartButton.js";
import {Score} from "./js/player/Score.js";

export class Main {
    constructor() {
        this.myCanvas = document.getElementById('game_canvas');
        this.context = this.myCanvas.getContext('2d');
        this.director = Director.getInstance();
        this.dataStore = DataStore.getInstance();
        const loader = ResourceLoader.create();
        loader.onLoaded(map => this.onResourceFirstLoaded(map));
    }

    onResourceFirstLoaded(map) {
        this.dataStore.canvas = this.myCanvas;
        this.dataStore.ctx = this.context;
        this.dataStore.res = map;
        this.init();
    }

    init() {
        this.director.isGameOver = false;
        this.dataStore
            .put("pencils", [])
            .put('background', BackGround)
            .put("land", Land)
            .put("birds", Birds)
            .put('score', Score)
            .put('startButton', StartButton);
        this.registerEvent();
        //创建铅笔要在游戏逻辑运行之前
        this.director.createPencil();
        this.director.run();
        // let background = new BackGround(this.context, map.get('background'));
        // background.draw()
    }

    registerEvent() {
        this.myCanvas.addEventListener('touchstart', e => {
            e.preventDefault();
            if (this.director.isGameOver) {
                this.init();
            } else {
                this.director.birdsEvent();
            }
        });

    }
}